package com.example.weixinsystem.service.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.weixinsystem.service.SysRoleService;
import com.example.weixinsystem.mapper.SysRoleMapper;
import com.weixin.common.core.constant.CacheConstants;
import com.weixin.common.core.entity.SysRole;
import com.weixin.common.core.form.PageForm;
import com.weixin.common.core.form.RoleAddForm;
import com.weixin.common.core.utils.SecurityUtil;
import com.weixin.common.core.vo.RoleListVo;
import com.weixin.common.redis.service.RedisService;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 *
 */
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {
    private RedisService redisService;

    public SysRoleServiceImpl(RedisService redisService) {
        this.redisService = redisService;
    }

    /**
     * 添加角色
     *
     * @param addForm
     */
    @Override
    public void addRole(RoleAddForm addForm) {
        SysRole role = new SysRole();
        BeanUtils.copyProperties(addForm, role);
        role.setCreatedBy(SecurityUtil.getUserName());
        role.setCreatedTime(DateUtil.date());
        this.save(role);
    }

    /**
     * 分页查询角色列表
     *
     * @param pageForm 分页参数
     * @param param    查询参数
     * @return 返回集合列表
     */
    @Override
    public IPage<RoleListVo> getRolePage(PageForm pageForm, RoleListVo param) {
        Page<RoleListVo> page = new Page<>(pageForm.getPageIndex(), pageForm.getPageSize());
        Set<Integer> pageRoleId = getRoleIdPage(page, param);
        // Map<Integer, SysRole> roleList = redisService.getMultiCacheMapValue(CacheConstants.ROLE_KEY, Collections.singleton(pageRoleId));
        return null;
    }

    /**
     * 获取用户拥有的角色
     *
     * @param userId 用户ID
     * @return
     */
    @Override
    public Set<String> getUserPossessRole(Integer userId) {
        return null;
    }


    private Set<Integer> getRoleIdPage(Page<RoleListVo> page, RoleListVo param) {
        LambdaQueryWrapper<RoleListVo> wrapper = new LambdaQueryWrapper<>();
        if (ObjectUtils.isNotEmpty(param.getId())) {
            wrapper.eq(RoleListVo::getId, param.getId());
        }
        if (StringUtils.isNotEmpty(param.getRoleKey())) {
            wrapper.eq(RoleListVo::getRoleKey, param.getRoleKey());
        }
        return this.baseMapper.queryRoleIdByPage(page, wrapper);
    }
}
